package com.doumuxie.controller;


import com.doumuxie.dto.UserDto;
import com.doumuxie.model.AuthRequest;
import com.doumuxie.service.AuthService;
import com.doumuxie.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

import static com.doumuxie.dto.UserDto.USER_SESSION_KEY;


/**
 * @author doumuxie
 * @version 1.0
 * @date 2020/2/7 11:06
 * @description 控制层
 **/
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @GetMapping("/login")
    public ResultUtil login(AuthRequest authRequest, HttpSession session) {
        UserDto result = authService.auth(authRequest);
        session.setAttribute(USER_SESSION_KEY, result);
        return ResultUtil.success(result);
    }

    @GetMapping("/logout")
    public ResultUtil logout(HttpSession session) {
        session.invalidate();
        return ResultUtil.success();
    }

    @GetMapping("/r1")
    public ResultUtil r1(HttpSession session) {
        Object attribute = session.getAttribute(USER_SESSION_KEY);
        if (attribute == null) {
            return ResultUtil.error("未登录");
        }
        UserDto dto = (UserDto) attribute;
        return ResultUtil.success(dto.getUsername()+"访问资源r1");
    }

    @GetMapping("/r2")
    public ResultUtil r2(HttpSession session) {
        Object attribute = session.getAttribute(USER_SESSION_KEY);
        if (attribute == null) {
            return ResultUtil.error("未登录");
        }
        UserDto dto = (UserDto) attribute;

        return ResultUtil.success(dto.getUsername()+"访问资源r2");

    }


}
